import Vue from 'vue';
import Utils from './util';
import Config from '../config';

/**
 * 如果不是手机端，则无法使用html5plus，则会使用到该plus文件，
 * 该plus主要：
 *  1、适配PC端无法使用html5plus的情况，使通过window.plus.xxx方式调用的api不会报错
 *  2、扩展html5plus的api，完善html5plus的一些不足
 *  
 * 该文件主要是适配和扩展，如果需要重写html5plus的api的话看replus.js文件
 */
var _plus = Utils.extend({}, {
  // 这里加上扩展的方法，对象，变量定义等等
  isWindows: false,
  isAndroid() {
    let osname = window.qmplus.os.name.toLowerCase();
    return "android" == osname;
  }, 
  isIOS() {
    let osname = window.qmplus.os.name.toLowerCase();
    return "ios" == osname;
  }, 
  isMobile() {
    return !!window.plus;
  }, 
  isElectron() {
    return !!window.electron;
  }, 
  isWeb() {
    return !(window.qmplus.isMobile() || window.qmplus.isElectron());
  }, 
  isHtml5PlusReady() {
    return !!window.plus;
  }, 
  camera: {
    getCamera() {

    }
  },
  device: {
    uuid: '',
  },
  runtime: {
    appid: '',
    version: '',
    install() {

    },
    getProperty() {

    }
  },
  os: {
    name: 'Windows'
  },
  gallery: {
    pick(successCB, errorCB, options) {
      var filter = [{
        name: 'Images',
        extensions: ['jpg', 'png', 'gif']
      }];
      window.ipcRenderer.send('selectFile', filter);
      window.ipcRenderer.once("fileSelected", function (event, file) {
        if (successCB) {
          successCB(file);
        }
      });
    }
  },
  key: {
    addEventListener(eventName, callback) {
      document.addEventListener(eventName, callback, false);
    }
  },
  share: {
    sendWithSystem(msg, successCB, errorCB) {
      vue.$f7.actions.create({
        grid: true,
        buttons: [
          [{
            text: '分享到',
            label: true
          }, ],
          [{
              text: '微信',
              icon: '<img src="' + Config.server + '/images/o_img_wechat.png" width="48"/>',
              onClick: function () {
                let popup = vue.$f7.popup.get(".f7-share-popup");
                if (popup) {
                  popup.open();
                }
              }
            },
            {
              text: 'QQ好友',
              icon: '<img src="' + Config.server + '/images/o_img_qq.png" width="48">',
              onClick: function () {
                let _shareUrl = 'https://connect.qq.com/widget/shareqq/iframe_index.html?';
                _shareUrl += 'url=' + encodeURIComponent(msg.href);
                _shareUrl += '&title=' + encodeURIComponent(msg.title);
                window.open(_shareUrl, '_blank');
              }
            },
            {
              text: 'QQ空间',
              icon: '<img src="' + Config.server + '/images/o_img_zone.png" width="48">',
              onClick: function () {
                let _shareUrl = 'http://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?';
                _shareUrl += 'url=' + encodeURIComponent(msg.href);
                _shareUrl += '&showcount=' + 0;
                _shareUrl += '&desc=' + encodeURIComponent(msg.title);
                _shareUrl += '&title=' + encodeURIComponent(msg.title);
                _shareUrl += '&pics=' + encodeURIComponent(msg.pictures || '');
                window.open(_shareUrl, '_blank');
              }
            },
          ],
          [{
              text: '新浪微博',
              icon: '<img src="' + Config.server + '/images/o_img_xlwb.png" width="48"/>',
              onClick: function () {
                let _shareUrl = 'http://v.t.sina.com.cn/share/share.php?';
                _shareUrl += 'url=' + encodeURIComponent(msg.href || '');
                _shareUrl += '&title=' + encodeURIComponent(msg.title);
                _shareUrl += '&source=' + encodeURIComponent('');
                _shareUrl += '&sourceUrl=' + encodeURIComponent('');
                _shareUrl += '&content=' + 'utf-8';
                _shareUrl += '&pic=' + encodeURIComponent(msg.pictures || '');
                window.open(_shareUrl, '_blank');
              }
            },
            {
              text: '豆瓣',
              icon: '<img src="' + Config.server + '/images/o_img_db.png" width="48">',
              onClick: function () {
                var _shareUrl = 'http://shuo.douban.com/!service/share?';
                _shareUrl += 'href=' + encodeURIComponent(msg.href);
                _shareUrl += '&name=' + encodeURIComponent(msg.title);
                _shareUrl += '&image=' + encodeURIComponent(msg.pictures || '');
                window.open(_shareUrl, '_blank');
              }
            },
            {
              text: '人人网',
              icon: '<img src="' + Config.server + '/images/o_img_renren.png" width="48">',
              onClick: function () {
                var _shareUrl = 'http://widget.renren.com/dialog/share?';
                _shareUrl += 'link=' + encodeURIComponent(msg.href);
                _shareUrl += '&title=' + encodeURIComponent(msg.title);
                window.open(_shareUrl, '_blank');
              }
            },
          ]
        ]
      }).open();
    }
  },
  io: {
    resolveLocalFileSystemURL() {

    },
    convertLocalFileSystemURL(filename) {
      return "file:///" + filename;
    },
    getRemoteURL(filepath) {
      return new Promise((resolve, reject) => {
        window.qmplus.io.resolveLocalFileSystemURL(
          filepath,
          function(entry) {
            resolve(entry.toRemoteURL());
          }, 
          function(error) {
            resolve(false);
          }
        );
      });
    }
  },
  uploader: {
    createUpload(url, options, callback) {
      let defaultOptions = {};
      let formData = new FormData();

      let task = {
        url: url + "?time=" + new Date().getTime(),
        options: Utils.extend({}, options, defaultOptions),
        callback: callback,
        addData(name, value) {
          formData.append(name, value);
        },
        addFile(path, params) {
          let lastIndex = path.lastIndexOf("/");
          if (lastIndex == -1) {
            lastIndex = path.lastIndexOf("\\");
          }
          let name = path.substr(lastIndex + 1);

          window.ipcRenderer.send('newFile', path);

          window.ipcRenderer.once("getFile", function (event, {
            data
          }) {

            let file = new File([data], name, {
              type: 'image/jpg'
            });
            formData.append(params.key, file);

            let xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
              if (xhr.readyState == 4 && xhr.status == 200) {
                callback(xhr, xhr.status);
              }
            }

            xhr.open(task.options.method, task.url, true);

            // 发送请求
            xhr.send(formData);
          });
        },
        start() {

        }
      };

      return task;
    }
  },
  downloader: {
    startAll() {

    },
    enumerate(eachCB, state) {
      // 从数据库里获取
      Vue.prototype.$db.downloadRecord.orderBy('downloadDate').desc().toArray(function (array) {
        eachCB(array);
      });
    },
    createDownload(url, options) {
      var defaultOptions = {};
      var dtask = {
        id: '',
        url: url,
        state: -1,
        options: Utils.extend({}, options, defaultOptions),
        filename: '',
        downloadedSize: 0,
        totalSize: 0,
        callback: null,
        abort() {
          vue.$f7.dialog.close();
        },
        addEventListener(eventName, callback) {
          dtask.callback = callback;
        },
        pause() {

        },
        resume() {

        },
        setRequestHeader() {

        },
        start() {
          // 发送信号
          window.ipcRenderer.send('download', dtask.url);

          window.ipcRenderer.on("setFilename", function (event, filename) {
            dtask.filename = filename;
          });
          window.ipcRenderer.on("pause", function (event, state) {
            dtask.state = state;
          });
          window.ipcRenderer.on("progressing", function (event, jsonData) {
            dtask.state = jsonData.state;
          });
          window.ipcRenderer.on("resume", function (event, state) {
            dtask.state = state;
          });
          window.ipcRenderer.on("completed", function (event, jsonData) {
            dtask.state = jsonData.state;
            dtask.totalSize = jsonData.totalSize;
            dtask.downloadedSize = jsonData.receivedSize;
            // 重新设置保存路径
            dtask.filename = jsonData.savePath;
            if (dtask.callback) {
              dtask.callback(dtask);
            }
          });
          window.ipcRenderer.on("failed", function (event, state) {
            dtask.state = state;
            dtask.abort();
          });
        }
      };

      return dtask;
    }
  },
  storage: {
    setItem(key, value) {
      vue.$framework.store.set(key, value);
    },
    getItem(key) {
      return vue.$framework.store.get(key);
    },
    removeItem(key) {
      vue.$framework.store.remove(key);
    }
  },
  net: {
    XMLHttpRequest() {
      return new XMLHttpRequest();
    }
  },
  nativeObj: {
    Bitmap() {

      return {
        loadBase64Data() {

        }
      };
    }
  },
  nativeUI: {
    alert(text) {
      vue.$f7.dialog.alert(text);
    },
    showWaiting() {
      vue.$f7.preloader.close = vue.$f7.preloader.hide;
      vue.$f7.preloader.closeWaiting = vue.$f7.preloader.hide;
      vue.$f7.preloader.show();
      return vue.$f7.preloader;
    },
    close() {
      vue.$f7.preloader.hide();
    },
    closeWaiting() {
      vue.$f7.preloader.hide();
    },
    actionSheet(options, callback) {
      var buttons = [{
        text: options.title || "请选择",
        label: true
      }, ];
      Utils.each(options.buttons, function (b, i) {
        buttons.push({
          text: b.title,
          onClick: function (actions, e) {
            if (callback) {
              callback({
                index: 2
              });
            }
          }
        });
      });
      buttons.push({
        text: options.cancel,
        color: "red"
      });
      vue.$f7.actions.create({
        buttons: buttons
      }).open();
    }
  },
  zip: {
    compressImage(options, successCB, errorCB) {
      if (successCB) {
        successCB(options.srcPath);
      }
    }
  },
});

export default _plus;
